<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||	
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws. 
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.). 
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations). 
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Groups/classes/PhpFox_ServiceGroupForum.class.php, $Author:  $ */



/** Service for working with groups
 * 
 * @package module.groups
 * @version $Id: PhpFox_ServiceGroupForum.class.php 46 2007-12-14 23:12:21Z phpfoxsv $
 *  Max Kovrigovich
 */
class PhpFox_Mod_Groups_ServiceGroupForum extends BaseService 
{
    /**
     * Load forum topics
     *
     * @param array $aCond
     * @param int $iPage
     * @param int $iPageSize
     * @param string $sOrder
     * @return array of topics and total count
     */
    function getTopicList($aCond, $iPage = 0, $iPageSize = 0, $sOrder = '')
    {
        $oItem = &$this->_oModule->getItem('GroupForum');
        $aMap = $oItem->aFields;

        $aMap['group_id'] = 'gf.group_id';

        $sCond = $oItem->_parseCond($aCond, $aMap);

        $sSql = 'SELECT COUNT(id) FROM `'.$oItem->sTable.'` AS '.$oItem->sAlias.' WHERE '.$sCond;
        $iCnt = $oItem->oDb->getField($sSql);
        
        $sSql = '
        SELECT gf.*, COUNT(repl.id)-1 AS count_replies, MAX(repl.id) AS last_reply
		FROM `'.$oItem->sTable.'` gf
		LEFT JOIN `'.$oItem->sTable.'` repl ON(gf.id = repl.reply_id)
		WHERE '.$sCond.' AND gf.id = gf.reply_id '.
		'GROUP BY gf.id
		ORDER BY '.($sOrder?$sOrder:' gf.time DESC ').' '.
		($iPage?(' LIMIT '.($iPage - 1)*$iPageSize.','.$iPageSize):'');
        
        $aTopics = $oItem->oDb->getRows($sSql, true, 'id');
        $aIds = array(0);
        foreach($aTopics as $aItem)
        {
            $aIds[] = $aItem['last_reply'];
        }
        //load last reply info
        $sSql = 'SELECT gf.user, gf.time, u.location, gf.reply_id
				 FROM `'.$oItem->sTable.'` AS gf
				 LEFT JOIN `'.App::getT('user').'` u ON(gf.user=u.user)
				 WHERE gf.id IN ('.implode(',', $aIds).')';
        $aReplyInfo = $oItem->oDb->getRows($sSql, true, 'reply_id');

        foreach($aTopics as $nKey=>$aItem)
        {
            $aTopics[$nKey]['last_user'] = (isset($aReplyInfo[$nKey]))?$aReplyInfo[$nKey]['user']:'';
            $aTopics[$nKey]['last_time'] = (isset($aReplyInfo[$nKey]))?$aReplyInfo[$nKey]['time']:'';
            $aTopics[$nKey]['last_location'] = (isset($aReplyInfo[$nKey]))?$aReplyInfo[$nKey]['location']:'';
        }

        return array($aTopics, $iCnt);
        //$sSql = 'SELECT id, group_id, reply_id, user, ';
    }

    /**
     * Load post data
     *
     * @param int $iPostId
     * @return array
     */
    function getPost($iPostId)
    {
        $oItem = &$this->_oModule->getItem('GroupForum');
        $sSql = 'SELECT * FROM `'.$oItem->sTable.'` WHERE `id`='.$iPostId;
        return $oItem->oDb->getRow($sSql);
    }
    
    /**
     * Load topic replies
     *
     * @param array $aCond
     * @param int $iPage
     * @param int $iPageSize
     * @param string $sOrder
     * @param object $oUser
     * @return array of posts and total count
     */
    function getTopicPosts($aCond, $iPage = 0, $iPageSize = 0, $sOrder = '', $oUser = '')
    {
        $oItem = &$this->_oModule->getItem('GroupForum');
        $aMap = $oItem->aFields;

        $aMap['reply_id'] = 'gf.reply_id';

        $sCond = $oItem->_parseCond($aCond, $aMap);

        $sSql = 'SELECT COUNT(id) FROM `'.$oItem->sTable.'` AS '.$oItem->sAlias.' WHERE '.$sCond;
        $iCnt = $oItem->oDb->getField($sSql);
        $iPage = ceil(min($iCnt / $iPageSize, $iPage));
        $sSql = '
        SELECT gf.*, u.headline, u.type as user_type, p.total AS user_points
		FROM `'.$oItem->sTable.'` gf
		JOIN `'.App::getT('user').'` u ON(gf.user=u.user)
		LEFT JOIN '. App::getT('user_info') .' AS p ON(u.id = p.id)
		WHERE '.$sCond. 
		($sOrder?(' ORDER BY '.$sOrder):'').
		($iPage?(' LIMIT '.($iPage - 1)*$iPageSize.','.$iPageSize):'');
        
        $aTopics = $oItem->oDb->getRows($sSql, true, 'id');
	    if($oUser)
	    {
	        $aKeys = array_keys($aTopics);
		    foreach($aKeys as $k)
		    {
		     if($aTopics[$k]['user'] == $oUser->aData['user'])   
		         $aTopics[$k]['owner'] = 1;
		    }
	    }
        return array($aTopics, $iCnt);
    }
    
    /**
     * Add view counter for topic
     *
     * @param int $iTopicId
     */
    function markTopicView($iTopicId)
    {
        $oItem = &$this->_oModule->getItem('GroupForum');
        $sSql = 'UPDATE `'.$oItem->sTable.'` SET `views` = (`views` + 1) WHERE `id`='.$iTopicId;
		$oItem->oDb->query($sSql);
    }
    
    /**
     * Edit or add a new post
     *
     * @param array $aParams field and values
     * @param int $iTopicId
     * @param int $iPostId
     * @return int record id
     */
    function editPost($aParams, $iTopicId = 0, $iPostId = 0)
    {
        App::loadClass('Text');
        $oTxt = &new Text();
 
        $oItem = &$this->_oModule->getItem('GroupForum');
        if($iPostId)
        {
            $oItem->aData['title'] = '"'.mysql_escape_string(htmlspecialchars($aParams['title'])).'"';
            $oItem->aData['text'] = '"'.mysql_escape_string(str_replace(array('&lt;', '&gt;', '&quot;', '&amp;'), array('<', '>', '"', '&'), $aParams['text'])).'"';
            $oItem->aData['id'] = $iPostId;
            $oItem->update(array(), false);
            return $iPostId;
        }
        else
        {
            $oItem->aData['user'] = '"'.$aParams['user'].'"';
            $oItem->aData['title'] = '"'.mysql_escape_string(htmlspecialchars($aParams['title'])).'"';
            $oItem->aData['text'] = '"'.mysql_escape_string(str_replace(array('&lt;', '&gt;', '&quot;', '&amp;'), array('<', '>', '"', '&'), $aParams['text'])).'"';
            $oItem->aData['time'] = $aParams['time'];
            $oItem->aData['type'] = '"'.$aParams['type'].'"';
            $oItem->aData['group_id'] = intval($aParams['group_id']);
            $oItem->aData['reply_id'] = intval($aParams['reply_id']);
            $oItem->insert(false);
            $iPostId = $oItem->oDb->getLastID();
            return $iPostId;
        }
    }
    
    /**
     * Delete post
     *
     * @param int $iPostId
     */
    function deletePost($iPostId)
    {
        $oItem = &$this->_oModule->getItem('GroupForum');
        $aPost = $this->getPost($iPostId);
        $sSql = 'DELETE FROM `'.$oItem->sTable.'` WHERE `id`='.$iPostId;
        $oItem->oDb->query($sSql);
        if($aPost['type'] != 'reply')
        {
            $sSql = 'DELETE FROM `'.$oItem->sTable.'` WHERE `reply_id`='.$iPostId;
            $oItem->oDb->query($sSql);
        }
    }
    
    
    /**
     * Add a new topic
     *
     * @param array $aParams fields and values
     * @return int topic id
     */
    function addTopic($aParams)
    {
        App::loadClass('Text');
        $oTxt = &new Text();
        $oItem = &$this->_oModule->getItem('GroupForum');

		//insert
		$oItem->aData['user'] = '"'.$aParams['user'].'"';
        $oItem->aData['title'] = '"'.mysql_escape_string(htmlspecialchars($aParams['title'])).'"';
        $oItem->aData['text'] = '"'.mysql_escape_string(str_replace(array('&lt;', '&gt;', '&quot;', '&amp;'), array('<', '>', '"', '&'), $aParams['text'])).'"';
        $oItem->aData['time'] = $aParams['time'];
        $oItem->aData['type'] = '"'.$aParams['type'].'"';
        $oItem->aData['group_id'] = intval($aParams['group_id']);
        //$oItem->aData['reply_id'] = (isset($aParams['reply_id']) ? intval($aParams['reply_id']) : '');
        $oItem->insert(false);
         
		$iPostId = $oItem->oDb->getLastID();
		$sSql = 'UPDATE `'.$oItem->sTable.'` SET `reply_id`="'.$iPostId.'" WHERE `id`="'.$iPostId.'"';
		$oItem->oDb->query($sSql);
		return $iPostId;
   }
}
?>